package com.example.my.nanyibangz.ui.mine;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.my.nanyibangz.MainActivity;
import com.example.my.nanyibangz.R;
import com.example.my.nanyibangz.base.BaseFragment;
import com.example.my.nanyibangz.bean.CollectionBeans;
import com.example.my.nanyibangz.ui.danpintypeclick.DanPinTypeClickLowerActivity;
import com.example.my.nanyibangz.ui.mine.adapter.SingleCollectionAdapter;
import com.example.my.nanyibangz.utils.CustomGridView;
import com.example.my.nanyibangz.utils.CustomerNestScrollView;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2016/10/20.
 * 我的收藏-单品
 */

public class SingleFragment extends BaseFragment {

    @Bind(R.id.cgv_single_collection)
    CustomGridView cgvSingleCollection;
    @Bind(R.id.txt_singel_collection)
    TextView txtSingelCollection;
    @Bind(R.id.ll_collection_singel_footer)
    LinearLayout llCollectionSingelFooter;
    @Bind(R.id.nsv_single_collection)
    CustomerNestScrollView nsvSingleCollection;
    @Bind(R.id.single_collection_srfl)
    SwipeRefreshLayout singleCollectionSrfl;
    private List<CollectionBeans> list;//存放收藏在数据中的单品集合。
    SingleCollectionAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.single_fragment, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        InitView(); //先从数据库中查询收藏的单品
        GridViewItemClick(); //dpTypeClickCgv。中每一项的点击事件
        LongGridViewClickDelete();  //gridview实现长安删除
        SwipRefeshLayout();//实现下拉刷新。
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    //先从数据库中查询收藏的单品
    public void InitView() {
        QueryBuilder<CollectionBeans, Long> builder = MainActivity.collectionBeansDao.queryBuilder();
        try {
            list = builder.orderBy("_id", false).query();
            Log.i("yy", "size==" + list.size());
            adapter = new SingleCollectionAdapter(getActivity(), list);
            cgvSingleCollection.setAdapter(adapter);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    //dpTypeClickCgv。中每一项的点击事件
    public void GridViewItemClick() {
        cgvSingleCollection.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent1 = new Intent(getActivity(), DanPinTypeClickLowerActivity.class);
                String item_id = list.get(position).getItem_id() + "";
                String title = list.get(position).getTitle();
                String price = list.get(position).getPrice() + "";
                String picUrl = list.get(position).getImgUrl();
                intent1.putExtra("itemId", item_id);//像购买商品详情界面传递，itemId,title,pic_url,price;
                intent1.putExtra("title", title);
                intent1.putExtra("price", price + "");
                intent1.putExtra("picUrl", picUrl);
                startActivity(intent1);
                getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
            }
        });
    }

    //gridview实现长安删除
    public void LongGridViewClickDelete() {

        cgvSingleCollection.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

                //    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                //    设置Title的内容
                builder.setTitle(list.get(position).getTitle());
                //    设置Content来显示一个信息
                builder.setMessage("确定删除吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //删除操作
                        /**
                         * 方法二：ORMLite原生的更新语句
                         * 在DAO的函数不满足你的灵活性时，可能用到原生的更新语句，
                         * 更新语句，必须包含保留关键字，INSERT,DELETE 或则UPDATE.
                         */
                        try {
                            MainActivity.collectionBeansDao.updateRaw("DELETE FROM collectionbeans WHERE item_id=" + list.get(position).getItem_id());
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }


                    }
                });
                //    设置一个NegativeButton
                builder.setNegativeButton("取消", null);
                //    显示出该对话框
                builder.show();
                return true;//只要长按事件返回true就可以了。解决长按点击和点击item冲突问题
            }
        });
    }
    //swipRefreshLayout实现下拉刷新，
    public void SwipRefeshLayout() {
        //设置研祥进度条的颜色，最多四种。；
        singleCollectionSrfl.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorSwipRef));
        singleCollectionSrfl.setColorSchemeResources(R.color.color_holo_yellow, R.color.color_holo_green, R.color.color_holo_he, R.color.color_holo_he2);

        singleCollectionSrfl.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));//调整进度条距离屏幕顶部的距离
        singleCollectionSrfl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        InitView();
                        singleCollectionSrfl.setRefreshing(false);
                    }
                }, 3000);
            }
        });
    }

}
